package com.huaqin.obeacons.bluetooth;

import java.util.Date;

import com.huaqin.obeacons.R;
import com.huaqin.obeacons.utils.MyDatabaseUtil;
import com.huaqin.obeacons.utils.SharedPreferenceUtil;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.os.Vibrator;
import android.util.Log;
import android.widget.Toast;

public class DeviceScanService extends Service {
	private final String TAG = "DeviceScanService";
	private final int IBEACON_SCAN_PERIOD = 1000;
	private Context mContext;
	private BluetoothAdapter mBluetoothAdapter;
	private Handler mHandler;
	private boolean mScanning;
	private long oldSaveDataTime;
	private long oldSaveRequestTime;

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		Log.d(TAG, "onCreate");
		super.onCreate();
		initData();
		initBluetooth();

	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		Log.d(TAG, "onStartCommand");
		scanLeDevice(true);
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		Log.d(TAG, "onBind");
		return null;
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		Log.d(TAG, "onDestroy");
		super.onDestroy();
		scanLeDevice(false);
	}

	private void initData() {
		mContext = this;
		mScanning = false;
		mHandler = new Handler();
		oldSaveDataTime = 0;
		oldSaveRequestTime = 0;
	}

	public void initBluetooth() {
		Log.d(TAG, "initBluetooth");
		// Use this check to determine whether BLE is supported on the device.
		// Then you can
		// selectively disable B mLeDevices.add(ibeacon);LE-related features.
		if (!mContext.getPackageManager().hasSystemFeature(
				PackageManager.FEATURE_BLUETOOTH_LE)) {
			Toast.makeText(mContext, R.string.ble_not_supported,
					Toast.LENGTH_SHORT).show();
		}

		// Initializes a Bluetooth adapter. For API level 18 and above, get a
		// reference to
		// BluetoothAdapter through BluetoothManager.
		final BluetoothManager bluetoothManager = (BluetoothManager) mContext
				.getSystemService(Context.BLUETOOTH_SERVICE);
		mBluetoothAdapter = bluetoothManager.getAdapter();
		// Checks if Bluetooth is supported on the device.
		if (mBluetoothAdapter == null) {
			Toast.makeText(mContext, R.string.error_bluetooth_not_supported,
					Toast.LENGTH_SHORT).show();
		}
		// Ensures Bluetooth is enabled on the device. If Bluetooth is not
		// currently enabled,
		// fire an intent to display a dialog asking the user to grant
		// permission to enable it.
		if (!mBluetoothAdapter.isEnabled()) {
			// 通知用户请求开启蓝牙
			// Intent intent = new
			// Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
			// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			// startActivity(intent);
			// 系统自动开启蓝牙
			mBluetoothAdapter.enable();
		}
	}

	private void scanLeDevice(final boolean enable) {
		Log.d(TAG, "scanLeDevice enable " + enable);
		if (enable) {
			// Stops scanning after a pre-defined scan period.
			mScanning = true;
			mBluetoothAdapter.startLeScan(mLeScanCallback);
			mHandler.postDelayed(scanDeviceRun, IBEACON_SCAN_PERIOD);
		} else {
			mScanning = false;
			mBluetoothAdapter.stopLeScan(mLeScanCallback);
		}
	}

	private final Runnable scanDeviceRun = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			Log.d(TAG, "mBluetoothAdapter mScanning " + mScanning);
			if (mScanning) {
				Log.d(TAG, " mBluetoothAdapter scan restart");
				mBluetoothAdapter.stopLeScan(mLeScanCallback);
				mBluetoothAdapter.startLeScan(mLeScanCallback);
			}
			mHandler.postDelayed(scanDeviceRun, IBEACON_SCAN_PERIOD);
		}

	};
	public BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

		@Override
		public void onLeScan(final BluetoothDevice device, int rssi,
				byte[] scanRecord) {
			Log.d(TAG, "BluetoothAdapter LeScanCallback");
			final IBeacon ibeacon = IBeacon.fromScanData(scanRecord, rssi,
					device);
//			Log.i("chaoyongan",
//					"device Address: " + device.getAddress() + " rssi:" + rssi
//							+ " getProximityUuid: "
//							+ ibeacon.getProximityUuid());
			// 创建一个bundle对象
			Bundle bundle = new Bundle();
			bundle.putSerializable("obeacons", ibeacon);
			// 发送广播
			Intent intent = new Intent();
			intent.putExtras(bundle);
			intent.setAction("com.huaqin.obeacons.updateIBeaconData");
			sendBroadcast(intent);
			saveDataToRecored(ibeacon);

		}
	};

	private void saveDataToRecored(IBeacon ibeacon) {
		Log.d("chaoyongan", "saveDataToRecored oldSaveDataTime "
				+ oldSaveDataTime + " oldSaveRequestTime " + oldSaveRequestTime);
		if (ibeacon != null && ibeacon.getRssi() > -70) {
			if (SystemClock.elapsedRealtime() - oldSaveDataTime > 5 * 60 * 1000) {
				if (SystemClock.elapsedRealtime() - oldSaveRequestTime > 2 * 1000) {
					MyDatabaseUtil
							.insertDateTimeHelpExtra(mContext, new Date());
					oldSaveDataTime = SystemClock.elapsedRealtime();
					hadnleRemindEvent();
				}
			}
			oldSaveRequestTime = SystemClock.elapsedRealtime();
		}
	}

	private void hadnleRemindEvent() {
		// TODO Auto-generated method stub
		if (SharedPreferenceUtil.getAppVoiceEnable(mContext)) {
			Uri notification = RingtoneManager
					.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
			Ringtone ring = RingtoneManager.getRingtone(mContext, notification);
			ring.setStreamType(AudioManager.STREAM_SYSTEM);
			ring.play();
		}
		if (SharedPreferenceUtil.getAppVibrateEnable(mContext)) {
			Vibrator vibrator = (Vibrator) mContext
					.getSystemService(Context.VIBRATOR_SERVICE);
			vibrator.vibrate(300);
		}
	};
}
